package com.neuedu.corejava.ch14;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Chat implements Runnable{

	public Socket socket = null;
	
	public Chat(Socket client) {
		this.socket=client;
	}
	
	@Override
	public void run() {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		//设置缓存，发生数据长度不能大于512字节
		byte[] buffer = new byte[512];
		boolean chatting = true;
		
		try {
			inputStream = socket.getInputStream();
			outputStream = socket.getOutputStream();
			
			 while(chatting){
				 //等待并接受客户端发生的数据，有阻塞作用
				 int len = inputStream.read(buffer);	
				 String  words = new String(buffer, 0, len).trim();
				 words= "parrot:"+ words;
				 //鹦鹉学舌，发送原话为客户端
				 System.out.println(words);
				 outputStream.write(("parrot ：" + words).getBytes());
				 

			
				 
				 if("quit".equalsIgnoreCase(words)) {
					 chatting =false;
				 }
				 
			 }
			 
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(outputStream!=null) {
				try {
					outputStream.close();
				} catch (IOException e) {
				}
			}
			if(inputStream!=null) {
				try {
					inputStream.close();
				} catch (IOException e) {
				}
			}
			if(socket!=null) {
				try {
					socket.close();
				} catch (IOException e) {
				}
			}
			if(socket!=null) {
				try {
					socket.close();
				} catch (IOException e) {
				}
			}
		}
	}
}
